const mysql = require('mysql2'),
  http = require('http'),
  url = require('url');

const conn = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'linux2016',
  database: 'linux'
});

http.createServer(function(req, res) {
  var pathname = url.parse(req.url).pathname;
  req.setEncoding('utf8');
  if (pathname != '/mysql') {
    res.writeHead(404, {
      'Content-Type': 'text/plain'
    });
    res.write('404 Not Found');
    res.end();
  } else {
    conn.query('SELECT * FROM mock', function(err, rows, fields) {
      if (err) throw err;
      res.writeHead(200, {
        'Content-Type': 'application/json'
      });
      var data = {};
      data.from = 'nodejs';
      data.list = rows;
      res.write(JSON.stringify(data));
      res.end();
    });
  }
}).listen(3000);
